<!--围栏管理 -->
<template>
  <div class="fence-manage-main" :style="customStyle">
    <div class="fence-main-content">
      <div ref = "leftDivId" class="fence-device-list" v-show="!leftBtn.collapsed"  >
        <OrgFenceTree ref="orgFenceTree"
          @fence-node-click="fanceNodeClick"
          @fence-org-click="fenceOrgClick"
          @fence-node-mouseover="fenceNodeMouseOver"
          @fence-node-mouseleave="fenceNodeMouseleave"
        />
      </div>

      <div ref="mapDiv1" class="fence-map-content" >
        <FenceMap ref="fenceMap"
                  :action="actions"
                  @save-of-new="saveNewFence"
                  @save-of-edit="saveEditFence"
                  @remove-fence="remove"
                  @fence-event="fenceEvent"
        >
        </FenceMap>
      </div>
      <div class="fence-left-expland-collapsible-button" :style="leftBtn.buttonStyle">
        <Button type="default"
                :Title="leftBtn.title"
                :icon="leftBtn.icon"
                style="margin-left: -2px" @click="leftBtnClick"/>
      </div>
    </div>
    <FenceManageEdit ref="fenceManageEdit" @after-save-cancel="afterSave"/>
  </div>
</template>
<script>
import OrganizationTree from '@/components/topnav/OrganizationTree'
import UserSelect from '_c/topnav/UserModelSelect'
import SearchHeader from '@/view/Common/SearchHeader'
import TopnavPage from '_c/topnav/TopnavPage'
import FenceManageEdit from '@/view/Fence/FenceManageEdit'
import OrgFenceTree from '@/view/Fence/OrgFenceTree'
import Fence from '@/api/Fence'
import {apiResult, clone} from "@/libs/util";
import FenceMap from "@/view/Fence/FenceMap";
export default {
  name: 'FenceManage',
  components:{OrganizationTree,UserSelect,SearchHeader,TopnavPage,FenceManageEdit,OrgFenceTree,FenceMap},
  watch:{
    collapsedSideMenu(){
      this.$nextTick(() => {
        this.setButtonStyle();
      })
    }
  },
  computed:{
    collapsedSideMenu() {
      //浮动的按钮重新定位置
      return this.$store.state.app.collapsedSideMenu;
    },
    columns(){
      return [{ title: this.$t('operate'), key: 'action', width: 100, slot: 'action', align: 'center' },
        { title: this.$t('name'), key: 'fenceName', sortable: true, width: 250, align: 'left',ellipsis:true,tooltip:true,tooltipTheme:'light'  },
        { title: this.$t('organization'), key: 'shortName', sortable: true, width: 250, align: 'left',ellipsis:true,tooltip:true,tooltipTheme:'light'  },]
    },
  },
  data(){
    return{
      api: new Fence(),
      actions:null,
      currentOrgId:null, //当前选中的部门ID
      leftBtn:{
        state: 1, //0关闭 1展开
        icon:"ios-arrow-back",
        title: "Close",
        collapsed: false,
        left: "0px",
        buttonStyle:{left: "500px"},
        boxWidth:320// offsetWidth 保存在这里，当div不可见，div 是没有创建的，不能访问offsetWidth
      },
      currentMapInfo:"《高德地图 街道》，级别：11",
      currentLocate:"112.34353, 22.343553",
      customStyle:{
        height: '300px'
      },


      queryParam: {
        page: {
          pages: 1,
          size: 15,
          total: 0,
          current: 1,
        },
        where: {
          keyword: null,
          code: null,
          name: null,
          fenceName: null,
          orgId: null,
          userId: null
        },
        init:()=>{
          this.queryParam.where.fenceName = null;
          this.queryParam.where.orgId = null;
        }
      },
      tableData:[],

    }
  },
  methods:{
    /**
     * 新增
     * @param data
     */
    add(data) {

      this.$refs.fenceMap.addFence((data,event)=>{
        //画图，完成后点保存或取消
        console.log("新增画图完成：data=%o,event=%o",data,event);
      });
    },

    /**
     * 取消不保存
     */
    afterSave(fdfd){
      this.actions=null;
      this.$refs.fenceMap.afterSave();
    },
    /**
     * 修改
     */
    edit(data) {
      let row = {
        id: data.id,
        note: data.arrt.note,
        fenceName: data.fenceName,
        orgId: data.arrt.orgId,
        coordinateSystem: data.arrt.coordinateSystem,
        coordinate: data.arrt.coordinate
      }
      //console.log("FenceManage.fenceNodeBtnClick data=%o",data)
      this.actions="edit";
      this.$refs.fenceMap.editFence(row);
    },

    /**
     * 围栏画图事件
     */
    fenceEvent(event,coordinate){
      const that = this;
      // event = save/cancel coordinate=[[[经度,纬度]]]
      if (event == "save") {
        if (!coordinate) {
          this.$Message.error(this.$t('add_fence_first'))
          return;
        }

        if (this.actions == "edit") {
          this.$refs.fenceManageEdit.openDialog("EDIT", row,
            () => {
              that.$refs.orgFenceTree.loadChildData(that.currentOrgId);})
        }else if (this.actions == "new") {
          //去掉对象里原生属性
          Object.setPrototypeOf(coordinate, null);
          //再转Base64
          let base64Str = btoa(JSON.stringify(coordinate));

          let row = {
            id: null,
            note: null,
            createTime: null,
            updateTime: null,
            createBy: null,
            updateBy: null,
            fenceName: null,
            orgId: this.currentOrgId,
            fenceType: 1,
            coordinateSystem: null,
            coordinate: base64Str
          }

          //BASE64 --> 再转回 GeoJSON
          /*        let destGeoJson = atob(base64Str)
          console.log("destJson=%o",destGeoJson);

          let destObject = JSON.parse(destGeoJson);
          console.log("destObject=%o",destObject);*/

        }


      }else if (event == "cancel"){
      }

    },
    /**
     * 点击新增，修改，删除按钮
     * @param event
     * @param node
     * @param data
     */
    fenceOrgClick(node, data){
      /**
       * new 新增
       * edit 修改
       * remove 删除
       */
      let row = {
        id: null,
        note: null,
        fenceName: null,
        orgId: data.arrt.orgId,
        coordinateSystem: null,
        coordinate: null
      }
      this.$refs.fenceMap.canAdd(row);

/*      if (event == "new"){
        this.add(data);
      }else if (event == "edit"){
        let row = {
          id: data.id,
          note: data.arrt.note,
          fenceName: data.fenceName,
          orgId: data.arrt.orgId,
          coordinateSystem: data.arrt.coordinateSystem,
          coordinate: data.arrt.coordinate
        }
        console.log("FenceManage.fenceNodeBtnClick data=%o",data)
        this.actions="edit";
        //this.$refs.fenceMap.editFence(row,data.arrt.coordinate);
      }else if (event == "remove"){
        this.$Message.error("删除围栏！");
      }*/
    },

    /**
     * 点击围栏时
     * @param node
     * @param data
     */
    fanceNodeClick(node, data){
      console.log("FenceManage.fanceNodeClick data=%o",data)
      let row = {
        id: data.arrt.fenceId,
        note: data.arrt.note,
        fenceName: data.arrt.fenceName,
        orgId: data.arrt.orgId,
        coordinateSystem: data.arrt.coordinateSystem,
        coordinate: data.arrt.coordinate
      }
      console.log("FenceManage.fanceNodeClick row=%o",row)
      this.$refs.fenceMap.redrawFence(row);
    },
    /**
     * 地图改变后
     */
    getMapInfo(event){
      this.currentMapInfo=event;
    },
    /**
     * 取当前定位信息
     */
    getLocate(event){
      this.currentLocate=event;
    },


    popupBtnClick(event,node, data){
    },
    leftBtnClick(){
      const that = this;
      if (this.leftBtn.state == 1){
        //当前展开状态
        this.leftBtn.state = 0;
        this.leftBtn.icon = "ios-arrow-forward"
        this.leftBtn.title = this.$t('map_tool_unfold')
        this.leftBtn.collapsed = true;
        //this.leftBtn.buttonStyle.left = "0px";
        if (!!this.$refs.leftDivId){
          this.leftBtn.boxWidth = this.$refs.leftDivId.offsetWidth;
        }
        this.$refs.fenceMap.refreshMap();
      }else{
        //当前关闭状态
        this.leftBtn.state = 1;
        this.leftBtn.icon = "ios-arrow-back"
        this.leftBtn.title = this.$t('map_tool_fold')
        this.leftBtn.collapsed = false;
        //this.leftBtn.buttonStyle.left = this.leftBtn.boxWidth + "px";
/*        this.$nextTick(() => {
          this.$refs.fenceMap.refreshMap();
        })*/
      }
      this.$nextTick(() => {
        that.$refs.fenceMap.refreshMap();
        that.setButtonStyle();
      })
      //this.setButtonStyle();
    },
    setButtonStyle(){
      let leftW = 0;
      if (!this.collapsedSideMenu){
        leftW = 257+18;
      }else{
        leftW = 82;
      }
/*
      if (!this.leftBtn.collapsed){
        leftW = leftW + this.leftBtn.boxWidth+18;
      }
*/
      if (!!this.$refs.leftDivId){
        leftW = leftW + this.$refs.leftDivId.offsetWidth;
      }

      this.leftBtn.buttonStyle.left = leftW+'px';

      //this.leftBtn.buttonStyle.left = this.leftBtn.boxWidth + "px";
    } ,
    getData(){
      /** 生成查询条件 */
      this.queryParam.page.current = (this.queryParam.page.pages - 1)* this.queryParam.page.size;
      this.api.queryPage(JSON.stringify(this.queryParam)).then(res => {
        this.tableData = [];
          apiResult(res.data,false,result=>{
            this.queryParam.page.total = result.data.total;
            this.tableData = result.data.records;
          })
      })
    },




    view(row) {
      this.$refs.fenceManageEdit.openDialog("VIEW",clone(row), this.getData);
    },
    remove (row) {
      this.$Modal.confirm({
        title: this.$t('delete_confirm'),
        content: this.$t('delete_make_sure'),
        onOk: () => {
          this.api.remove(JSON.stringify(row)).then(res=>{
            apiResult(res.data,true,result=>{
              this.getData();
              this.$refs.fenceMap.afterRemove();
              this.$refs.orgFenceTree.getData();
            });
          })
        },
        onCancel: () => {}
      });
    },
    fenceNodeMouseOver(node,data){

    },
    fenceNodeMouseleave(node,data){

    },

    saveEditFence(row,coordinate){
      //console.log(">>>>>>>> FenveManage.saveEditFence row=%o,coordinate=%o",row,coordinate);
      row.coordinate = coordinate;
      this.$refs.fenceManageEdit.openDialog("EDIT", clone(row),
        (result) => {
          //console.log(">>>>>>>> FenveManage.saveEditFence result=%o",result);
        if (result == 1){
          this.$refs.orgFenceTree.getData();
          this.$refs.fenceMap.afterSave();
        }
      });
    },
    saveNewFence(row,coordinate){
/*      let row = {
        id: null,
        fenceName: null,
        orgId: this.currentOrgId,
        fenceType: 1,
        coordinateSystem: null,
        coordinate: coordinate,
        note: null,
      };*/
      row.coordinate = coordinate;
      this.$refs.fenceManageEdit.openDialog("ADD", row,
        (result) => {
          if (result == 1){
            this.$refs.orgFenceTree.getData();
            this.$refs.fenceMap.afterSave();
          }
        });
    }
  },
  mounted() {
    const offsetHeight = 128+40+36 //菜单头 128，框架头 40 框架 padding 18 *2
    const _this = this;
    this.setButtonStyle();
    this.customStyle = {height: document.body.clientHeight - offsetHeight+"px"};
    this.$nextTick(() => {
      _this.$refs.fenceMap.refreshMap();
    })
    window.onresize = function(){
      if (!offsetHeight) return;
      //_this.$Message.info("窗口大小已经改变" + document.body.clientHeight);
      console.log("窗口大小已经改变" + document.body.clientHeight);
      _this.customStyle = {height: document.body.clientHeight - offsetHeight+"px"};
      _this.$nextTick(() => {
        if (!!_this.$refs.fenceMap){
          _this.$refs.fenceMap.refreshMap();
        }
        _this.setButtonStyle();
      })
    }
  }
}
</script>
<style lang="less">
@import ".././template";

.fence-manage-main{
  width: 100%;
  //height: calc(~"100% - 64px");
  height: 500px;
  //border: 1px solid #aff;
  display: flex;
  flex-direction: row;
  .fence-head-content{
    width: 100%;
    height: 64px;
  }
  .fence-main-content{
    width: 100%;
    height: 100%;
    //background: #00060c;
    display: flex;
    flex-direction: row;
    .fence-device-list{
      width: 300px;
      height: 100%;
      overflow: auto;
      //background: #056b05;
    }
    //滚动条设置
    .fence-device-list::-webkit-scrollbar { /*滚动条整体样式*/
      width: 10px; /*高宽分别对应横竖滚动条的尺寸*/
      height: 10px;
    }

    .fence-device-list::-webkit-scrollbar-thumb { /*滚动条里面小方块*/
      border-radius: 10px;
      -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0,0.3);
      background: rgba(0, 0, 0,0.1);
    }

    .fence-map-content{
      width: 100%;
      height: 100%;
      //border: 1px solid #056b05;
      //background: #0b54dc;

    }
  }

  .fence-left-expland-collapsible-button{
    height: 37px !important;
    width: 37px;
    position: fixed;
    left: 500px;
    //top:100px;
    top: calc(~"(100% - 64px - 37px) / 2");
    border-bottom-right-radius: 5px;
    border-top-right-radius: 5px;
    border-radius: 2px;
    //background: #c80000;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-content: center;
  }

}
</style>
